package com.hk.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.hk.constants.MqConstants;
import com.hk.exception.BizException;
import com.hk.rabbitmq.config.ConfirmConfig;
import com.hk.rabbitmq.domain.User;
import com.hk.rabbitmq.service.Json2UserMessageConverter;
import com.hk.rabbitmq.service.demo.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author: dpb
 * @date: 2022/4/7
 */
@Component
@Slf4j
public class ConfirmConsumer {

    public static final String QUEUENAME = "chatbot";

    @Autowired
    private UserService userService;

    private static final Gson GSON = new Gson();

    /**
     * 监听queues队列
     * @param message
     */
    @RabbitListener(queues = QUEUENAME)
    public void receiveMsg(Message message){
        String msg = new String(message.getBody());
        log.info("ConfirmConsumer 接收到的消息为：{}" ,msg);
    }

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = MqConstants.QUEUE_NAME)
    public void receiverSync(Message message) {
        log.info("接口到消息，内容为：{}", JSON.toJSONString(message));
        byte[] body = message.getBody();
        User user = GSON.fromJson(new String(message.getBody(), StandardCharsets.UTF_8), User.class);
        List<User> list = userService.list(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (CollectionUtils.isEmpty(list)) {
            userService.save(user);
        }
    }

}
